package com.example.onlinetaxi.ui.activity.Driver.MainPage.WaitingOrderFragment;

import android.os.Bundle;

import androidx.fragment.app.Fragment;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.Toast;

import com.example.onlinetaxi.LocalStroage.LocalStorage;
import com.example.onlinetaxi.R;
import com.example.onlinetaxi.Thread.DriverReceiveOrderThread;
import com.example.onlinetaxi.callback.IExchangeFragments;
import com.example.onlinetaxi.util.OKHttpUtil.HttpUrl;
import com.example.onlinetaxi.util.OKHttpUtil.OKHttpUtil;
import com.example.onlinetaxi.view.CircleWaveView;

import java.util.HashMap;
import java.util.Map;

public class CancelGetOrderFragment extends Fragment {

    private View rootView;
    private Button cancelGetOrder;
    // 水波组件
    private CircleWaveView circleView;

    // fragment切换
    private IExchangeFragments iExchangeFragments;

    // 请求参数
    private Map<String, String> map = new HashMap<>();

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        rootView = inflater.inflate(R.layout.fragment_cancel_get_order, container, false);

        initView();

        initEvent();

        return rootView;
    }

    private void initEvent() {
        cancelGetOrder.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                iExchangeFragments.exchangeFragment();

                // 改变司机状态
                sendCancelGetOrderRequest();

                // 取消出车线程
                DriverReceiveOrderThread.finished = true;
                // 确保线程终止
                try {
                    Thread.sleep(1500);
                } catch (InterruptedException e) {
                }
                DriverReceiveOrderThread.thread = null;
                DriverReceiveOrderThread.bestOrderCallBack = null;

                Toast.makeText(getActivity(), "您已取消出车！", Toast.LENGTH_SHORT).show();
            }
        });

        // 启动水波
        circleView.start();
    }

    public void sendCancelGetOrderRequest() {
        map.clear();

        map.put("phone", LocalStorage.phone);
        // 进入接单模式
        map.put("state", "0");

        OKHttpUtil.postAsyncRequest(HttpUrl.getBaseUrl(), map, "driver", "changeGetOrderState");
    }

    private void initView() {
        cancelGetOrder = rootView.findViewById(R.id.driver_cancel_get_order);
        // 获取水波移动组件
        circleView = rootView.findViewById(R.id.driver_circle);
    }

    public void setiExchangeFragments(IExchangeFragments iExchangeFragments) {
        this.iExchangeFragments = iExchangeFragments;
    }
}